import sys
import json
from emr.emr_cluster import EmrCluster
sys.path.append('emr/jobs/testing')


def spider_completed_handler(next_job, event, context):
    """
    handle events only source == 'pt.spider' and detail-type == 'Spider State-change Notification' and detail.state == 'COMPLETED'
    :param next_job:
    :param event:
    :param context:
    :return:
    """
    print("triggered spider_completed_handler: %s" % event)
    job_name = next_job["jobName"]
    if job_name:
        print("job name is %s..." % job_name)
        emrCluster = EmrCluster("PP_%s" % job_name)
        response = emrCluster.submit_job(job_name)
        print("done...response is...")
        print(response)
        return {
            'statusCode': 200,
            'body': json.dumps(response)
        }
    else:
        print("skipped trigger after flow to step %s..." % job_name)
        return {
            'statusCode': 200,
            'body': json.dumps({"msg": "skipped trigger after flow to step %s..." % job_name})
        }


def emr_completed_handler(next_job, event, context):
    """
    handle events only source == 'aws.emr' and detail-type == 'EMR Step Status Change' and detail.state == 'COMPLETED'
    :param next_job:
    :param event:
    :param context:
    :return:
    """
    print("triggered emr_completed_handler: %s" % event)
    step_name = event['detail']['name']
    job_name = next_job["jobName"]
    if job_name and "Debugging" not in step_name:
        emrCluster = EmrCluster("PP_%s" % job_name)
        response = emrCluster.submit_job(job_name)
        print("done...response is...")
        print(response)
        return {
            'statusCode': 200,
            'body': json.dumps(response)
        }
    else:
        print("skipped trigger after flow to step %s..." % step_name)
        return {
            'statusCode': 200,
            'body': json.dumps({"msg": "skipped trigger after flow to step %s..." % step_name})
        }
